package com.mall.malladminbackend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.malladminbackend.dto.Create;
import com.mall.malladminbackend.entity.Menu;
import com.mall.malladminbackend.entity.Role;
import com.mall.malladminbackend.mapper.MenuMapper;
import com.mall.malladminbackend.mapper.RoleMapper;
import com.mall.malladminbackend.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：郭立仁
 * 描述：永无BUG
 */
@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    public R all(){
        return R.buildSuccess(0,"success",roleMapper.selectAll());
    }

    @Transactional
    public R update(Role role, Create create){
        int update = roleMapper.update(role, create);
        return update>0? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }

    @Transactional
    public R insert(Role role,Create create){
        int insert = roleMapper.insert(role, create);
        return insert>0? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }

    @Transactional
    public R delete(Integer id){
        int i = roleMapper.deleteRoleAndMenu(id);
        int i1 = roleMapper.deleteRoleAndUser(id);
        int delete = roleMapper.delete(id);
        return (i+i1+delete)>0? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }

    //查询角色对应的菜单
    public R selectMenu(Integer id){
        List<Menu> menus = roleMapper.selectByRoleId(id);
        int[] ids = new int[menus.size()];
        for (int i = 0; i < menus.size(); i++) {
            ids[i] = menus.get(i).getId();
        }
        return ids.length>0? R.buildSuccess(0,"success",ids)
                : R.buildSuccess(100,"失败");
    }

    //修改查询角色对应的菜单
    public R updateMenu(Integer roleId,int[] menus,Create create){
        if (roleId!=null&&create!=null){
            if (menus.length==0){
                int i = roleMapper.deleteRoleAndMenu(roleId);
                return R.buildSuccess(0,"success");
            }else {
                int i1 = roleMapper.deleteRoleAndMenu(roleId);
                int i = roleMapper.insertRoleAndMenu(roleId, menus, create);
                return R.buildSuccess(0,"success");
            }
        }
        return R.buildSuccess(100,"失败");
    }

    //全选
    public R allchecked(){
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        QueryWrapper<Menu> id = qw.select("id");
        List<Menu> menus = menuMapper.selectList(id);
        int[] ids = new int[menus.size()];
        for (int i = 0; i < menus.size(); i++) {
            ids[i] = menus.get(i).getId();
        }
        return R.buildSuccess(0,"success",ids);
    }
}
